package cn.xo68.ide.plugin.common.service.impl;

import cn.xo68.core.PropertiesDocument;
import cn.xo68.core.common.Charsets;
import cn.xo68.core.date.DateTime;
import cn.xo68.core.util.JsonUtil;
import cn.xo68.ide.plugin.common.PluginPathUtils;
import cn.xo68.ide.plugin.common.domain.CodeGenerateInfo;
import cn.xo68.ide.plugin.common.domain.TableModuleConfig;
import cn.xo68.ide.plugin.common.service.CodeGenerateManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.wy2.generator.GeneratorByJdbcConnection;
import com.wy2.generator.database.common.DatabaseMetaDataEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CodeGenerateManagerImpl implements CodeGenerateManager {

    private static Logger logger = LoggerFactory.getLogger(CodeGenerateManagerImpl.class);

    @Override
    public PropertiesDocument loadGenerateConfig(VirtualFile projectVirtualFile) {
        String path= PluginPathUtils.getCodeGenereateConfigPath(projectVirtualFile);
        if(Files.notExists(Paths.get(path))) {
            return null;
        }
        PropertiesDocument propertiesDocument=new PropertiesDocument(true);
        try {
            propertiesDocument.loadAndMerge(null, true, path);
        } catch (IOException e) {
            logger.error("加载代码生成配置信息异常", e);
            return null;
        }
        return propertiesDocument;
    }

    @Override
    public CodeGenerateInfo loadCodeGenerateInfo(VirtualFile projectVirtualFile){
        String path= PluginPathUtils.getCodeGenereateInfoPath(projectVirtualFile);
        if(Files.notExists(Paths.get(path))) {
            return null;
        }
        CodeGenerateInfo codeGenerateInfo =null;

            try {
                codeGenerateInfo= JsonUtil.getInstance().read(new File(path), Charsets.UTF8, CodeGenerateInfo.class);
            } catch (Exception e) {
                logger.error("读取代码生成信息异常", e);
            }

        return codeGenerateInfo;
    }
    @Override
    public void saveCodeGenerateInfo(VirtualFile projectVirtualFile, CodeGenerateInfo codeGenerateInfo) {
        String path= PluginPathUtils.getCodeGenereateInfoPath(projectVirtualFile);
        try {
            JsonUtil.getInstance().save(codeGenerateInfo, true, new File(path), Charsets.UTF8);
        } catch (Exception e) {
            logger.error("保存代码生成信息异常", e);
        }
    }

    @Override
    public DatabaseMetaDataEntity loadLocalDatabaseMetaData(VirtualFile projectVirtualFile){
        String path= PluginPathUtils.getDatabaseMetaDataPath(projectVirtualFile);
        if(Files.notExists(Paths.get(path))) {
            return null;
        }
        DatabaseMetaDataEntity databaseMetaDataEntity =null;
        try {
            databaseMetaDataEntity=JsonUtil.getInstance().read(new File(path), Charsets.UTF8, DatabaseMetaDataEntity.class);

        } catch (Exception e) {
            logger.error("读取数据库元数据异常", e);
        }
        return databaseMetaDataEntity;
    }

    @Override
    public DatabaseMetaDataEntity loadRemoteDatabaseMetaData(VirtualFile projectVirtualFile){
        DatabaseMetaDataEntity databaseMetaDataEntity=null;
        PropertiesDocument configDoc=loadGenerateConfig(projectVirtualFile);
        if(configDoc==null){
            return null;
        }
        GeneratorByJdbcConnection generatorByJdbcConnection=new GeneratorByJdbcConnection(configDoc);
        try {
            databaseMetaDataEntity = generatorByJdbcConnection.getDatabaseMetaDataEntity(null);
        }catch (Exception e) {
            logger.warn("没有加载到任何表信息，请确认数据库连接配置是否正常");
            return null;
        }
        if(databaseMetaDataEntity==null || databaseMetaDataEntity.getTables().isEmpty()) {
            logger.warn("没有加载到任何表信息，请确认数据库中有表，或检查网络是否正常");
            return null;
        }

        try {
            if(databaseMetaDataEntity!=null || !databaseMetaDataEntity.getTables().isEmpty() || databaseMetaDataEntity.getTables().size() > 0) {
                String path= PluginPathUtils.getDatabaseMetaDataPath(projectVirtualFile);
                JsonUtil.getInstance().save(databaseMetaDataEntity, true, new File(path), Charsets.UTF8);
            }

        } catch (Exception e) {
            logger.error("写入数据库元数据异常", e);
        }

        return databaseMetaDataEntity;
    }

    @Override
    public DatabaseMetaDataEntity loadDatabaseMetaData(VirtualFile projectVirtualFile, boolean reload){
        DatabaseMetaDataEntity databaseMetaDataEntity=null;
        if(!reload) {
            databaseMetaDataEntity=loadLocalDatabaseMetaData(projectVirtualFile);
            if(databaseMetaDataEntity!=null && !databaseMetaDataEntity.getTables().isEmpty() && databaseMetaDataEntity.getTables().size()>0){
                return databaseMetaDataEntity;
            }
        }

        databaseMetaDataEntity=loadRemoteDatabaseMetaData(projectVirtualFile);



        return databaseMetaDataEntity;
    }

    @Override
    public TableModuleConfig loadTableModuleConfig(VirtualFile projectVirtualFile){
        String path= PluginPathUtils.getTableModuleConfigPath(projectVirtualFile);
        if(Files.notExists(Paths.get(path))) {
            return null;
        }
        TableModuleConfig moduleConfig=null;
        try {
            moduleConfig = JsonUtil.getInstance().read(new File(path), Charsets.UTF8, TableModuleConfig.class);
        } catch (Exception e) {
            logger.error("读取数据库表的模块数据异常", e);
        }
        return moduleConfig;
    }

    @Override
    public void saveTableModuleConfig(VirtualFile projectVirtualFile, TableModuleConfig moduleConfig) {
        String path= PluginPathUtils.getTableModuleConfigPath(projectVirtualFile);
        try {
            moduleConfig.setUpdateDate(DateTime.Now().toString());
            JsonUtil.getInstance().save(moduleConfig, true, new File(path), Charsets.UTF8);
        } catch (Exception e) {
            logger.error("保存模块信息异常", e);
        }
    }
}
